<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :destroy-on-close="true"
    :width="!props.isReadonly ? '600px' : '750px'"
    draggable
    :align-center="true"
    @close="closeDialog"
    style="min-width: 600px"
  >
    <el-form
      v-show="!props.isReadonly"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="90"
      style="width: 95%"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="作业类别" prop="taskKind">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.taskKind"
              placeholder="请选择作业类别"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('EamTaskKind')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName("EamTaskKind", formData.taskKind)
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="类型编号" prop="sopTypeCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.sopTypeCode"
              placeholder="请输入类型编号"
              clearable
            />

            <span v-else>{{ formData.sopTypeCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="类型名称" prop="sopTypeName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.sopTypeName"
              placeholder="请输入类型名称"
              clearable
            />

            <span v-else>{{ formData.sopTypeName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              type="textarea"
              v-model="formData.remarks"
              placeholder="请输入备注"
              show-word-limit
              :maxlength="250"
              :autosize="{ minRows: 3, maxRows: 4 }"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-if="!props.isReadonly" v-model="formData.enabled">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{
              dictionaryStore.filterDictName("Enabled", formData.enabled)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      title=""
      :column="2"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">作业类别</div>
        </template>
        {{ dictionaryStore.filterDictName("EamTaskKind", formData.taskKind) }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">类型编号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.sopTypeCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">类型名称</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.sopTypeName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否启用</div>
        </template>
        <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
        <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.remarks || "暂无备注" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "CommonWorkTypeEdit",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});

const visibleDialog = ref(false);

const formRef = ref(ElForm);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  taskKind: [{ required: true, message: "请选择作业类别", trigger: "change" }],
  sopTypeCode: [
    { required: true, message: "请输入类型编号", trigger: "blur" },
    { max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  sopTypeName: [
    { required: true, message: "请输入类型名称", trigger: "blur" },
    { min: 1, max: 50, message: "不能超过50个字符", trigger: "blur" },
  ],
  remarks: [
    { message: "请输入备注", trigger: "blur" },
    { max: 255, message: "不能超过255个字符", trigger: "blur" },
  ],
  enabled: [{ required: true, message: "请选择是否启用", trigger: "change" }],
});

let formData = reactive({
  id: "",
  version: "",
  taskKind: "",
  assetKind: props.assetKind,
  sopTypeCode: "",
  sopTypeName: "",
  remarks: "",
  organizationId: "",
  enabled: 1,
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        taskKind,
        assetKind,
        sopTypeCode,
        sopTypeName,
        remarks,
        organizationId,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        assetKind,
        sopTypeCode,
        sopTypeName,
        remarks,
        organizationId,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        taskKind: taskKind.toString(),
      });
    } else {
      formData.enabled = 1;
      formData.assetKind = props.assetKind;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.taskKind = "";
  formData.assetKind = props.assetKind;
  formData.sopTypeCode = "";
  formData.sopTypeName = "";
  formData.remarks = "";
  formData.organizationId = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 标准作业类型保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eamsoptype/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style lang="scss" scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 110px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
